import {
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProCard,
  FooterToolbar,
  DragSortTable,
} from '@ant-design/pro-components';

import { Badge, Button, message } from 'antd';
import { useEffect, useState } from 'react';
import { editPDAConfig, getPDAConfig } from '../service';
import TicketPreview from './TicketPreview';
import {
  DEFAULT_PRINT_KEY_ORDER,
  DEFAULT_TICKET_CONTENT,
  TICKE_KEY_MAP,
  getPrintKeyArr,
  getPrkingKeyMap,
} from './util';

const CAN_NOT_EDIT = new Set([
  'chargeCode',
  'chargeCodeTitle',
  'parkType',
  'officialCode',
  'officialText',
]);

const TicketConfigPages = (props: { ownerId: string; ifConfig: boolean }) => {
  const { ownerId, ifConfig = false } = props;
  const [form] = ProForm.useForm();
  const [prevConfig, setPrevConfig] = useState<TicketContentParams>(DEFAULT_TICKET_CONTENT);
  const [chillDowning, setChillDowning] = useState<number>(0);
  const [printKeys, setPrintKeys] = useState<PrintKeyItem[]>(DEFAULT_PRINT_KEY_ORDER);
  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  useEffect(() => {
    if (!ownerId) return;
    getPDAConfig(ownerId).then((res) => {
      if (!res?.success) {
        message.error({ content: '获取PDA配置失败', key: 'pda_config' });
        return;
      }
      form?.setFieldsValue(
        Object.assign({ ...DEFAULT_TICKET_CONTENT }, res?.data?.ticket) || DEFAULT_TICKET_CONTENT,
      );

      setPrevConfig(
        Object.assign({ ...DEFAULT_TICKET_CONTENT }, res?.data?.ticket) || DEFAULT_TICKET_CONTENT,
      );
      if (res?.data?.ticket?.printKeyOrder) {
        setPrintKeys(getPrintKeyArr(res?.data?.ticket?.printKeyOrder));
      }
    });
  }, [ownerId]);

  return (
    <ProCard>
      <ProCard
        title="小票配置"
        subTitle="* 本配置中，收费二维码及查询参数以外的配置，更改后需要收费员重新登录以生效"
        colSpan="640px"
      >
        <ProForm<PDATicketConfig>
          form={form}
          submitter={{
            searchConfig: {
              submitText: ifConfig ? '保存配置' : '无操作权限',
            },
            submitButtonProps: {
              disabled: !ifConfig || chillDowning > 0,
            },
            render: (_, dom) => (
              <FooterToolbar>
                <Button
                  onClick={() => {
                    if (!form) return;
                    form.validateFields();
                    const values = form.getFieldsValue();
                    const newObj = Object.assign({ ...DEFAULT_TICKET_CONTENT }, values);
                    setPrevConfig(newObj);
                  }}
                >
                  预览
                </Button>
                {dom}
              </FooterToolbar>
            ),
          }}
          onFinish={async (values) => {
            setChillDowning(5);
            const res = await editPDAConfig({
              ownerId,
              ticket: {
                ...values,
                printKeyOrder: getPrkingKeyMap(printKeys),
              },
            });
            if (!res?.success) {
              message.error({ content: 'PDA配置失败', key: 'pda_config' });
              return false;
            }
            message.success({ content: 'PDA配置成功', key: 'pda_config' });
            if (res.data) {
              if (res.data.ticket) {
                setPrevConfig(Object.assign(DEFAULT_TICKET_CONTENT, res.data?.ticket || {}));
                if (res.data.ticket.printKeyOrder) {
                  setPrintKeys(getPrintKeyArr(res.data.ticket.printKeyOrder));
                }
              }
            }

            return true;
          }}
          initialValues={prevConfig}
        >
          <ProFormText
            required
            width="xl"
            label="小票抬头"
            name="headerTitle"
            fieldProps={{
              maxLength: 10,
              showCount: {
                formatter: ({ count, maxLength }) => `${count}/${maxLength}`,
              },
            }}
          />
          <ProFormText
            required
            width="xl"
            label="收费单位"
            name="chargeParty"
            // fieldProps={{
            //   maxLength: 10,
            //   showCount: {
            //     formatter: ({ count, maxLength }) => `${count}/${maxLength}`,
            //   },
            // }}
          />
          <ProFormText required width="xl" label="收费二维码" name="chargeCode" />
          <ProFormSelect
            required
            width="xl"
            label="收费二维码查询参数"
            name="chargeCodeQueryKey"
            options={[
              { label: '车牌号码', value: 'plateNumber' },
              { label: '订单号', value: 'orderNo' },
            ]}
          />
          <ProFormText
            width="xl"
            label="收费码标题"
            name="chargeCodeTitle"
            initialValue="微信/支付宝"
          />
          <ProFormText
            width="xl"
            label="公众号二维码"
            placeholder="请输入公众号二维码"
            name="officialCode"
          />
          <ProFormText width="xl" label="客服电话" placeholder="请输入客服电话" name="serviceTel" />
          <ProFormTextArea
            label="公众号文字"
            width="xl"
            placeholder="请输入公众号文字描述"
            name="officialText"
          />

          <ProFormTextArea
            label="免责申明"
            width="xl"
            name="disclaimer"
            fieldProps={{
              rows: 10,
            }}
            placeholder="请输入免责申明，请注意自行换行"
          />
        </ProForm>
      </ProCard>
      <ProCard title="打印顺序配置" subTitle="* 本配置更改后需要收费员重新登录以生效">
        <DragSortTable<PrintKeyItem>
          dataSource={printKeys}
          options={false}
          search={false}
          pagination={false}
          editable={{
            onSave: async (key, row) => {
              console.log('onSave: ', key, row);

              if (row.index != undefined) {
                const newPrintKeys = [...printKeys];
                newPrintKeys[row.index] = {
                  enable: row.enable,
                  key: row.key,
                  title: row.title,
                };
                setPrintKeys(newPrintKeys);
              }
            },
            actionRender: (row, config, dom) => [dom.save, dom.cancel],
          }}
          columns={[
            {
              title: '排序',
              dataIndex: 'sort',
              width: 60,
              readonly: true,
            },
            {
              title: '字段名称',
              dataIndex: 'key',
              width: 150,
              readonly: true,
              render: (_, record) => {
                return TICKE_KEY_MAP[record.key];
              },
              // hideInTable: true,
            },
            {
              title: '打印标题',
              dataIndex: 'title',
              align: 'center',
              editable: (text, record, index) => {
                return !CAN_NOT_EDIT.has(record.key);
              },
              fieldProps: {
                maxLength: 7,
                showCount: true,
              },
              render: (_, record) => {
                return CAN_NOT_EDIT.has(record.key) ? '-' : record.title;
              },
            },
            {
              title: '是否启用',
              width: 150,
              dataIndex: 'enable',
              valueType: 'switch',
              align: 'center',
              render: (_, record) => {
                return record.enable ? (
                  <Badge text="启用" color="green" />
                ) : (
                  <Badge text="关闭" color="red" />
                );
              },
            },
            {
              title: '操作',
              valueType: 'option',
              width: 150,
              render: (_, record, x, action) => {
                return (
                  <a
                    key="editable"
                    onClick={() => {
                      if (action?.startEditable) {
                        action?.startEditable(record.key);
                      }
                    }}
                  >
                    编辑
                  </a>
                );
              },
            },
          ]}
          dragSortKey="sort"
          rowKey="key"
          onDragSortEnd={(newData) => {
            console.log('拖拽完成 ========》 ', newData);
            setPrintKeys(newData);
          }}
        />
      </ProCard>
      <ProCard colSpan="250px" ghost direction="column">
        {prevConfig && <TicketPreview ticketContent={prevConfig} printKeyOrder={printKeys} />}
      </ProCard>
    </ProCard>
  );
};
export default TicketConfigPages;
